package com.goods.link.binfan;

import com.goods.link.LinkProduct;
import com.thoughtworks.selenium.Wait;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.util.concurrent.TimeUnit;

/**
 * @author Dan
 * Created by zhengjunbo on 2015/9/14.
 */
public class BinFan {
    public LinkProduct findLinkProduct(final RemoteWebDriver driver,final String requestUrl){
        LinkProduct linkProduct = new LinkProduct();
        driver.get("http://www.bingfan.com/");
        driver.findElementByCssSelector("#bf_nav_product_url").sendKeys(requestUrl);
        driver.findElementByCssSelector("#bf_nav_product_url_button").click();
        final String currentUrl = driver.getCurrentUrl();
        new Wait() {
            @Override
            public boolean until() {
                System.out.println(driver.getCurrentUrl());
                if(currentUrl.equals(driver.getCurrentUrl())){
                    try2Click(driver, By.cssSelector("#bf_nav_product_url_button"));

                    return false;
                }
                return true;
            }
        }.wait("等待点击超时", 30000L,5000L);
        linkProduct.setUrl(driver.getCurrentUrl());
        String price = driver.findElementByCssSelector("#product_china_price").getText();
        linkProduct.setPrice(price);
        String shipPrice = driver.findElementByCssSelector("#bf_product_carriage").getText();
        linkProduct.setShipPrice(shipPrice.substring(1));
        return linkProduct;
    }

    private void try2Click(RemoteWebDriver driver,By by) {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

        try {
            driver.findElement(by).click();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        }
    }
}
